package com.hyc.seckillsystem.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @projectName: seckillsystem
 * @package: com.hyc.seckillsystem.util
 * @className: RedisUtil
 * @author: 冷环渊 doomwatcher
 * @description: TODO
 * @date: 2022/3/7 21:25
 * @version: 1.0
 */
@Component
public class RedisUtil {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    //    设置缓存
    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public void set(String key, Object value, long timeout) {
        redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
    }

    public Object get(String key) {
        if (!redisTemplate.hasKey(key)) {
            return null;
        }
        return redisTemplate.opsForValue().get(key);
    }

    public void decr(String key) {
        redisTemplate.opsForValue().decrement(key);
    }

    public Object execute(SessionCallback sessionCallback) {
        return redisTemplate.execute(sessionCallback);
    }

    public Object execute(RedisScript script, List keylist) {
        return redisTemplate.execute(script, keylist);
    }

    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }
}
